package com.lykj.llw.box.ui.activity

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.alipay.sdk.app.PayTask
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ThreadUtils
import com.bytedance.applog.game.GameReportHelper
import com.dinuscxj.itemdecoration.GridDividerItemDecoration
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.kwai.monitor.log.TurboAgent
import com.lykj.lib_base.base.BaseActivity
import com.lykj.lib_base.constants.BConstants
import com.lykj.lib_base.data.bean.response.UserInfoResponse
import com.lykj.lib_base.internal.extfun.clickWithTrigger
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.lib_base.net.http.CustomResponseBodyObserver
import com.lykj.lib_base.net.http.RetrofitManager
import com.lykj.llw.box.R
import com.lykj.llw.box.adapter.RechargePTBAdapter
import com.lykj.llw.box.data.bean.response.PTBRechargeResponse
import com.lykj.llw.box.data.entity.PayResult
import com.lykj.llw.box.data.model.RechargeOptionModel
import com.lykj.llw.box.databinding.ActPtbRechargeBinding
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody
import org.json.JSONObject

/**
 * ================================================
 * 平台币充值页面
 * ================================================
 *
 * @author gosha
 * @date 2023/10/16-11:19
 */
class PTBRechargeActivity : BaseActivity() {
    lateinit var binding: ActPtbRechargeBinding

    private val mAdapter = RechargePTBAdapter()
    private val mData = ArrayList<RechargeOptionModel>()
    private var mTextWatcher: TextWatcher? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActPtbRechargeBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initUI()
        initData()
        setListener()
    }

    override fun onResume() {
        super.onResume()

        ImmersionBar.with(this).transparentBar()
            .statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
            .navigationBarDarkIcon(true)
            .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
            .navigationBarEnable(false)
            .init()

        obtainPtbInfo()
    }

    override fun initUI() {
        if (!BConstants.isDebug) {
            binding.lltWx.visibility = View.GONE
        }
    }

    //平台币充值
    private fun ptbRecharge() {
        RetrofitManager.instance?.ptbRecharge(binding.etAmount.text.toString(),
            object : CustomResponseBodyObserver<ResponseBody>() {
                override fun onSubscribe(d: Disposable) {
                    addDisposables(this@PTBRechargeActivity, d)
                }

                override fun specificHandle(responseBody: String) {
                    val bean =
                        GsonUtils.fromJson(responseBody, PTBRechargeResponse::class.java)

                    if (null != bean.data) {
                        Thread {
                            val alipay = PayTask(this@PTBRechargeActivity)
                            val result = alipay.payV2(bean.data, true)
                            val payResult = PayResult(result)
                            val resultInfo: String? = payResult?.result // 同步返回需要验证的信息
                            val resultStatus: String? = payResult?.resultStatus
                            LogUtils.e(
                                "asd",
                                "alipay: $resultInfo::$resultStatus::$payResult"
                            )

                            var jsonObj = JSONObject(resultInfo)
                            var money = jsonObj.getJSONObject("alipay_trade_app_pay_response").getDouble("total_amount").toInt()
                            LogUtils.e("$money")

                            // 判断resultStatus 为9000则代表支付成功
                            if (TextUtils.equals(resultStatus, "9000")) {
                                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                                ThreadUtils.runOnUiThread {
                                    binding.etAmount.setText("")
                                    ToastUtils.showShort(this@PTBRechargeActivity, "支付成功")
                                    GameReportHelper.onEventPurchase(
                                        "",
                                        "",
                                        "",
                                        1,
                                        "支付宝",
                                        "¥",
                                        true,
                                        money
                                    )
                                    LogUtils.e("---------巨量用户支付---已上报---------")

                                    TurboAgent.onPay(money.toDouble())
                                    LogUtils.e("---------快手用户支付---已上报---------")
                                }
                                obtainPtbInfo()
                            } else {
                                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                                ThreadUtils.runOnUiThread {
                                    ToastUtils.showShort(this@PTBRechargeActivity, "支付失败")
                                }
                            }
                        }.start()
                    }
                }

                override fun handleException(ret: String, msg: String?) {
                    msg?.let {
                        ToastUtils.showShort(this@PTBRechargeActivity, it)
                    }
                }
            })
    }

    //获取用户平台币信息
    private fun obtainPtbInfo() {
        RetrofitManager.instance.obtainUserInfo(object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(responseBody, UserInfoResponse::class.java)

                binding.tvPtbAmount.text = "${bean.data?.ptbMoney}"

            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let { LogUtils.e("$msg") }
            }
        })
    }

    override fun initData() {
        val rom1 = RechargeOptionModel(50)
        val rom2 = RechargeOptionModel(300)
        val rom3 = RechargeOptionModel(500)
        val rom4 = RechargeOptionModel(1000)
        val rom5 = RechargeOptionModel(5000)
        val rom6 = RechargeOptionModel(10000)

        mData.add(rom1)
        mData.add(rom2)
        mData.add(rom3)
        mData.add(rom4)
        mData.add(rom5)
        mData.add(rom6)
        initRecyclerView()
    }

    private fun initRecyclerView() {
        val gridLayoutManager = GridLayoutManager(this, 3)
        gridLayoutManager.orientation = GridLayoutManager.VERTICAL
        binding.rcvRecharge.layoutManager = gridLayoutManager
        binding.rcvRecharge.setHasFixedSize(true)
        val dividerItemDecoration = GridDividerItemDecoration(
            this, GridDividerItemDecoration.GRID_DIVIDER_VERTICAL
        )
        dividerItemDecoration.setVerticalDivider(
            resources.getDrawable(
                R.drawable.divider_15dp, resources.newTheme()
            )
        )
        dividerItemDecoration.setHorizontalDivider(
            resources.getDrawable(
                R.drawable.divider_0dp, resources.newTheme()
            )
        )
        binding.rcvRecharge.addItemDecoration(dividerItemDecoration)
        mAdapter.data = mData
        mAdapter.setOnItemClickListener { adapter, view, position ->
            for (index in mData.indices) {
                mData[index].isCheck = index == position
            }

            binding.etAmount.setText("${mData[position].amount / 10}")
            binding.etAmount.setSelection(binding.etAmount.length())
            adapter.notifyDataSetChanged()
        }
        binding.rcvRecharge.adapter = mAdapter
    }

    override fun setListener() {
        binding.titleBar.ivBack.clickWithTrigger {
            finish()
        }

        binding.titleBar.tvRightOption.clickWithTrigger {
            startActivity(Intent(this, PTBRechargeRecordActivity::class.java))
        }

        binding.tvBtnRecharge.clickWithTrigger {
            if (binding.etAmount.text.isNullOrBlank()) {
                ToastUtils.showShort(this, "请先输入要充值的平台币金额")
                return@clickWithTrigger
            }

            ptbRecharge()
        }

//        mTextWatcher = DecimalInputTextWatcher(binding.etAmount, 9, 2)
//        binding.etAmount.addTextChangedListener(mTextWatcher)

        KeyboardUtils.registerSoftInputChangedListener(this) { height ->
            if (height == 0) {//软键盘收起,移除焦点
                binding.etAmount.clearFocus()
            }
        }
    }

    override fun onDestroy() {
        binding.etAmount.removeTextChangedListener(mTextWatcher)
        removeDisposables(this)
        super.onDestroy()
    }
}